﻿/*
 * WatchMyToon Plugin for HB
 *     Codebase
 *       2012
 *  
 * */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Styx.Helpers;
using Styx.Plugins.PluginClass;
using Styx.WoWInternals;
using System.Data.Odbc;
using System.Drawing;
using Styx;
using System.Text.RegularExpressions;
using System.Threading;
using Styx.Combat.CombatRoutine;
using System.Globalization;
using System.Windows.Forms;
using System.IO;
using System.Net;

namespace WatchMyToon
{
    class WatchMyToon : HBPlugin
    {
        ConfigForm conf = new ConfigForm();
        ScreenCapture scr = new ScreenCapture();

        public override string Name { get { return "WatchMyToon"; } }

        public override string Author { get { return "Codebase & CoDeRs"; } }

        public override Version Version { get { return new Version(1, 3, 6); } }

        public override bool WantButton { get { return true; } }

        public override void OnButtonPress()
        {
            conf.ShowDialog();
        }

        public const string dbVersion = "V1.3.5";

        public bool IsInitialized = false;

        public bool doWork = true;

        public bool CharInfoUpdated = false;

        private int nToonId;

        private string ConStr = "DSN=WatchMyToon_DB";
        private OdbcConnection connection;

        private DateTime last_update;

        public string Realm = string.Empty;
        public string Server = string.Empty;
        public string Side = string.Empty;

        private string[] ArrayClassSpec = new string[2] { "", "" };

        private string[] ArrayBagCount = new string[2] { "0", "0" };

        private int currentZoneId = 0;
        private int currentZoneLevel = 0;
        private int xposition = 0;
        private int yposition = 0;

        private bool stop = false;
        private Thread workerThread;

        // Updates
        //*****************

        // Update to V1.3.5
        private bool UpdateV135()
        {
            string newdbVersion = "V1.3.5";
            bool continueupdate = true;
            try
            {
                OdbcConnection conn = new OdbcConnection(ConStr);
                conn.Open();

                if (conn.State == System.Data.ConnectionState.Open)
                {
                    lock (conn)
                    {
                        Logging.Write(Color.Orange, "[WatchMyToon] - Update DB to Version: " + newdbVersion);

                        OdbcCommand create = conn.CreateCommand();

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "CREATE TABLE IF NOT EXISTS `TABScreenShots` (`nToonId` int(15) NOT NULL AUTO_INCREMENT,`nScreenShotNr` int(15) NOT NULL,`szPath` varchar(300) NOT NULL,`dtTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,PRIMARY KEY (`nToonId`, `nScreenShotNr`)) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "UPDATE `TABVersion` SET `szVersionName` = '" + newdbVersion + "';";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;
                    }
                }
                
                conn.Close();

                return true;
            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - Error while update to version " + newdbVersion + "  --> " + ex.Message);
                return false;
            }
            

        }

        // Update to V1.3.4
        private bool UpdateV134()
        {
            string newdbVersion = "V1.3.4";
            bool continueupdate = true;
            try
            {
                OdbcConnection conn = new OdbcConnection(ConStr);
                conn.Open();

                if (conn.State == System.Data.ConnectionState.Open)
                {
                    lock (conn)
                    {

                        Logging.Write(Color.Orange, "[WatchMyToon] - Update DB to Version: " + newdbVersion);

                        OdbcCommand create = conn.CreateCommand();

                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToons", "szPlatform"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToons` ADD `szPlatform` VARCHAR( 16 ) NOT NULL DEFAULT 'WOW' AFTER `szName`;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "ALTER TABLE `TABAchievements` CHANGE `nAchievLfd` `nAchievLfd` INT( 15 ) NOT NULL AUTO_INCREMENT ;";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "UPDATE `TABVersion` SET `szVersionName` = '" + newdbVersion + "';";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                    }
                }

                conn.Close();

                return true;
            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - Error while update to version " + newdbVersion + "  --> " + ex.Message);
                return false;
            }
        }

        // Update to V1.3.3
        private bool UpdateV133()
        {
            string newdbVersion = "V1.3.3";
            bool continueupdate = true;
            try
            {
                OdbcConnection conn = new OdbcConnection(ConStr);
                conn.Open();

                if (conn.State == System.Data.ConnectionState.Open)
                {
                    lock (conn)
                    {

                        Logging.Write(Color.Orange, "[WatchMyToon] - Update DB to Version: " + newdbVersion);

                        OdbcCommand create = conn.CreateCommand();

                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToonsDetail", "nZoneLevelNr"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToonsDetail` ADD `nZoneLevelNr` INT( 5 ) NULL AFTER `szZoneId`;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;


                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "UPDATE `TABVersion` SET `szVersionName` = '" + newdbVersion + "';";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                    }
                }

                conn.Close();

                return true;
            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - Error while update to version " + newdbVersion + "  --> " + ex.Message);
                return false;
            }
        }

        // Update to V1.3.2
        private bool UpdateV132()
        {
            string newdbVersion = "V1.3.2";
            bool continueupdate = true;
            try
            {
                OdbcConnection conn = new OdbcConnection(ConStr);
                conn.Open();

                if (conn.State == System.Data.ConnectionState.Open)
                {
                    lock (conn)
                    {

                        Logging.Write(Color.Orange, "[WatchMyToon] - Update DB to Version: " + newdbVersion);

                        OdbcCommand create = conn.CreateCommand();

                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToonsDetail", "nXposition"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToonsDetail` ADD `nXposition` INT( 5 ) NULL AFTER `nTotalBagSlot`;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToonsDetail", "nYposition"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToonsDetail` ADD `nYposition` INT( 5 ) NULL AFTER `nXposition`;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "UPDATE `TABVersion` SET `szVersionName` = '" + newdbVersion + "';";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                    }
                }

                conn.Close();

                return true;
            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - Error while update to version " + newdbVersion + "  --> " + ex.Message);
                return false;
            }
        }

        // Update to V1.3.1
        private bool UpdateV131()
        {
            string newdbVersion = "V1.3.1";
            bool continueupdate = true;
            try
            {
                OdbcConnection conn = new OdbcConnection(ConStr);
                conn.Open();

                if (conn.State == System.Data.ConnectionState.Open)
                {
                    lock (conn)
                    {

                        Logging.Write(Color.Orange, "[WatchMyToon] - Update DB to Version: " + newdbVersion);

                        OdbcCommand create = conn.CreateCommand();

                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToonsDetail", "nFreeBagSlot"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToonsDetail` ADD `nFreeBagSlot` INT( 5 ) NULL AFTER `bIsInParty`;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToonsDetail", "nTotalBagSlot"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToonsDetail` ADD `nTotalBagSlot` INT( 5 ) NULL AFTER `nFreeBagSlot`;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "UPDATE `TABVersion` SET `szVersionName` = '" + newdbVersion + "';";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                    }
                }

                conn.Close();

                return true;
            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - Error while update to version " + newdbVersion + "  --> " + ex.Message);
                return false;
            }
        }

        // Update to V1.3.0
        private bool UpdateV130()
        {
            string newdbVersion = "V1.3.0";
            bool continueupdate = true;
            try
            {
                OdbcConnection conn = new OdbcConnection(ConStr);
                conn.Open();

                if (conn.State == System.Data.ConnectionState.Open)
                {
                    lock (conn)
                    {
                        Logging.Write(Color.Orange, "[WatchMyToon] - Update DB to Version: " + newdbVersion);

                        OdbcCommand create = conn.CreateCommand();

                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToons", "szClass"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToons` ADD `szClass` VARCHAR( 50 ) NULL AFTER `szRace`;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;


                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToons", "szCurrentSpec"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToons` ADD `szCurrentSpec` VARCHAR( 50 ) NULL AFTER `szClass`;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "UPDATE `TABVersion` SET `szVersionName` = '" + newdbVersion + "';";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;
                    }
                }
                else
                    return false;

                conn.Close();

                return true;
            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - Error while update to version " + newdbVersion + "  --> " + ex.Message);
                return false;
            }
        }

        // Update to V1.2.0
        private bool UpdateV120()
        {
            string newdbVersion = "V1.2.0";
            bool continueupdate = true;
            try
            {
                OdbcConnection conn = new OdbcConnection(ConStr);
                conn.Open();

                if (conn.State == System.Data.ConnectionState.Open)
                {
                    lock (conn)
                    {
                        Logging.Write(Color.Orange, "[WatchMyToon] - Update DB to Version: " + newdbVersion);

                        OdbcCommand create = conn.CreateCommand();

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "CREATE TABLE IF NOT EXISTS `TABAchievements` (`nToonId` int(15) NOT NULL,`nAchievLfd` int(15) NOT NULL,`szAchievId` varchar(300) NOT NULL,PRIMARY KEY (`nToonId`,`nAchievLfd`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "CREATE TABLE IF NOT EXISTS `TABQuestLog` (`nToonId` int(15) NOT NULL,`nQuestId` int(15) NOT NULL,`szQuestName` varchar(200) NOT NULL,`nQuestLevel` int(5) NOT NULL,`nComplete` int(1) NOT NULL,PRIMARY KEY (`nToonId`,`nQuestId`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {

                                create.CommandText = "CREATE TABLE IF NOT EXISTS `TABGroupInvites` (`nToonId` int(15) NOT NULL,`szInviterName` varchar(50) NOT NULL,`szStatus` varchar(50) NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {

                                create.CommandText = "CREATE TABLE IF NOT EXISTS `TABGuildInvites` (`nToonId` int(15) NOT NULL,`szInviterName` varchar(50) NOT NULL,`szGuildName` varchar(50) NOT NULL,`szStatus` varchar(50) NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToonsDetail", "bIsInGuild"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToonsDetail` ADD `bIsInGuild` INT( 1 ) NULL AFTER `szMoneyInCopper`;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToonsDetail", "bIsInParty"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToonsDetail` ADD `bIsInParty` INT( 1 ) NULL AFTER `bIsInGuild`;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToonsDetail", "szGuildName"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToonsDetail` ADD `szGuildName` VARCHAR( 50 ) NULL AFTER `bIsInGuild`;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;


                        if (continueupdate)
                        {
                            try
                            {

                                create.CommandText = "CREATE TABLE IF NOT EXISTS `TABEventHandling` (`nToonId` int(15) NOT NULL, `nEventId` int(30) NOT NULL AUTO_INCREMENT,`szEventDesc` varchar(50) NOT NULL,`szEventText` varchar(200) NULL, PRIMARY KEY (`nToonId`,`nEventId`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "UPDATE `TABVersion` SET `szVersionName` = '" + newdbVersion + "';";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        create.Dispose();
                    }

                    conn.Close();
                    return true;
                }
                else
                    return false;


            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - Error while update to version " + newdbVersion + "  --> " + ex.Message);
                return false;
            }

        }

        // Update to V1.1.0
        private bool UpdateV110()
        {
            string newdbVersion = "V1.1.0";
            bool continueupdate = true;

            try
            {
                OdbcConnection conn = new OdbcConnection(ConStr);
                conn.Open();

                if (conn.State == System.Data.ConnectionState.Open)
                {
                    lock (conn)
                    {
                        Logging.Write(Color.Orange, "[WatchMyToon] - Update DB to Version: " + newdbVersion);

                        OdbcCommand create = conn.CreateCommand();

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "CREATE TABLE IF NOT EXISTS `TABMessageReceive` (`nMsgId` int(30) NOT NULL AUTO_INCREMENT,`nToonId` int(15) NOT NULL,`szMessageType` varchar(50) NOT NULL,`szMessagePartner` varchar(50) NOT NULL,`szMessageText` varchar(500) NOT NULL,`dtTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,PRIMARY KEY (`nMsgId`)) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "CREATE TABLE IF NOT EXISTS `TABMessageToSend` (`nMsgId` int(30) NOT NULL AUTO_INCREMENT,`nToonId` int(15) NOT NULL,`szMessageType` varchar(50) NOT NULL,`szMessagePartner` varchar(50) NOT NULL,`szMessageText` varchar(500) NOT NULL,`dtTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,PRIMARY KEY (`nMsgId`)) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "CREATE TABLE IF NOT EXISTS `TABToons` (`nToonId` int(15) NOT NULL AUTO_INCREMENT,`szGender` varchar(50) NOT NULL,`szRace` varchar(50) NOT NULL,`szName` varchar(50) NOT NULL,`dtLastUpdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,PRIMARY KEY (`nToonId`)) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "CREATE TABLE IF NOT EXISTS `TABToonsDetail` (`nToonId` int(15) NOT NULL,`nCurrentLvl` int(10) NOT NULL,`nCurrentXp` int(11) NOT NULL,`nNextLvlXp` int(11) NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToons", "szRealm"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToons` ADD `szRealm` VARCHAR( 100 ) NULL AFTER `nToonId`;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToons", "szFaction"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToons` ADD `szFaction` VARCHAR( 50 ) NULL AFTER `szRealm`;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "CREATE TABLE IF NOT EXISTS `TABLoots` (`nToonId` int(15) NOT NULL,`nLootNr` int(15) NOT NULL AUTO_INCREMENT,`szColor` varchar(100) NOT NULL,`szId` varchar(100) NOT NULL, `szName` varchar(200) NOT NULL,`szAmount` varchar(50) NOT NULL,`dtInsert` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,PRIMARY KEY (`nToonId`,`nLootNr`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToonsDetail", "szHealth"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToonsDetail` ADD `szHealth` VARCHAR( 200 ) NULL ,ADD `szZoneId` VARCHAR( 200 ) NULL ,ADD `szSubZone` VARCHAR( 200 ) NULL ,ADD `szZoneText` VARCHAR( 200 ) NULL;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToonsDetail", "szPowerType"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToonsDetail` ADD `szPowerType` VARCHAR( 50 ) NULL AFTER `nNextLvlXp` ,ADD `szPower` VARCHAR( 50 ) NULL AFTER `szPowerType`;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                if (!CheckForColumn("TABToonsDetail", "szMoneyInCopper"))
                                {
                                    create.CommandText = "ALTER TABLE `TABToonsDetail` ADD `szMoneyInCopper` VARCHAR( 20 ) NULL AFTER `szZoneText`;";
                                    create.ExecuteNonQuery();
                                }
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        if (continueupdate)
                        {
                            try
                            {
                                create.CommandText = "UPDATE `TABVersion` SET `szVersionName` = '" + newdbVersion + "';";
                                create.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                continueupdate = false;
                            }
                        }
                        else
                            return false;

                        create.Dispose();

                    }

                    conn.Close();
                    return true;
                }
                else
                    return false;

            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - Error while update to version V1.0.0  --> " + ex.Message);
                return false;
            }

        }

        //*****************

        // look for update
        private void VersionControl()
        {
            try
            {

                if (connection.State == System.Data.ConnectionState.Open)
                {
                    lock (connection)
                    {
                        bool tabversionexist = false;
                        try
                        {
                            OdbcCommand check = connection.CreateCommand();
                            check.CommandText = "Select * from TABVersion;";
                            check.ExecuteNonQuery();
                            check.Dispose();

                            tabversionexist = true;
                        }
                        catch (Exception ex)
                        {
                            Logging.Write(Color.Orange, "[WatchMyToon] - TabVersion does not exist, creating!");
                            tabversionexist = false;
                        }

                        if (!tabversionexist)
                        {
                            OdbcCommand create = connection.CreateCommand();
                            create.CommandText = "CREATE TABLE IF NOT EXISTS `TABVersion` (`szVersionName` varchar(50) NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
                            create.ExecuteNonQuery();
                            create.CommandText = "INSERT INTO `TABVersion` (`szVersionName`) VALUES ('V0.0.0');";
                            create.ExecuteNonQuery();
                            tabversionexist = true;
                        }

                        if (tabversionexist)
                        {
                            bool updtodate = false;

                            while (!updtodate)
                            {
                                OdbcCommand command = new OdbcCommand("SELECT * FROM `TABVersion`;", connection);
                                OdbcDataReader reader = command.ExecuteReader();

                                while (reader.Read())
                                {
                                    string currentVersion = reader["szVersionName"].ToString();

                                    switch (currentVersion)
                                    {
                                        case "V0.0.0":
                                            if (UpdateV110())
                                                Logging.Write(Color.Green, "[WatchMyToon] - Update done");
                                            else
                                            {
                                                Logging.Write(Color.Red, "[WatchMyToon] -Error while update");
                                                doWork = false;
                                                return;
                                            }
                                            break;
                                        case "V1.1.0":
                                            if (UpdateV120())
                                                Logging.Write(Color.Green, "[WatchMyToon] - Update done");
                                            else
                                            {
                                                Logging.Write(Color.Red, "[WatchMyToon] -Error while update");
                                                doWork = false;
                                                return;
                                            }
                                            break;
                                        case "V1.2.0":
                                            if (UpdateV130())
                                                Logging.Write(Color.Green, "[WatchMyToon] - Update done");
                                            else
                                            {
                                                Logging.Write(Color.Red, "[WatchMyToon] -Error while update");
                                                doWork = false;
                                                return;
                                            }
                                            break;
                                        case "V1.3.0":
                                            if (UpdateV131())
                                                Logging.Write(Color.Green, "[WatchMyToon] - Update done");
                                            else
                                            {
                                                Logging.Write(Color.Red, "[WatchMyToon] -Error while update");
                                                doWork = false;
                                                return;
                                            }
                                            break;
                                        case "V1.3.1":
                                            if (UpdateV132())
                                                Logging.Write(Color.Green, "[WatchMyToon] - Update done");
                                            else
                                            {
                                                Logging.Write(Color.Red, "[WatchMyToon] -Error while update");
                                                doWork = false;
                                                return;
                                            }
                                            break;
                                        case "V1.3.2":
                                            if (UpdateV133())
                                                Logging.Write(Color.Green, "[WatchMyToon] - Update done");
                                            else
                                            {
                                                Logging.Write(Color.Red, "[WatchMyToon] -Error while update");
                                                doWork = false;
                                                return;
                                            }
                                            break;
                                        case "V1.3.3":
                                            if (UpdateV134())
                                                Logging.Write(Color.Green, "[WatchMyToon] - Update done");
                                            else
                                            {
                                                Logging.Write(Color.Red, "[WatchMyToon] -Error while update");
                                                doWork = false;
                                                return;
                                            }
                                            break;
										case "V1.3.4":
                                            if (UpdateV135())
                                                Logging.Write(Color.Green, "[WatchMyToon] - Update done");
                                            else
                                            {
                                                Logging.Write(Color.Red, "[WatchMyToon] -Error while update");
                                                doWork = false;
                                                return;
                                            }
                                            break;
                                        case dbVersion:
                                            Logging.Write(Color.Green, "[WatchMyToon] - DB is up to date");
                                            updtodate = true;
                                            break;

                                    }

                                }

                                reader.Close();
                                reader.Dispose();
                                command.Dispose();

                            }


                        }


                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - Error while VersionControl  --> " + ex.Message);
            }
        }

        // Check if the Column already exists
        private bool CheckForColumn(string TableName, string ColumnName)
        {
            bool exists = false;
            try
            {
                if (connection.State == System.Data.ConnectionState.Open)
                {
                    lock (connection)
                    {
                        string SQLQuery = "SELECT count(*) AS Anzahl FROM `information_schema`.`COLUMNS` WHERE `TABLE_NAME` = \"" + TableName + "\" AND `COLUMN_NAME` = \"" + ColumnName + "\";";
                        OdbcCommand check = connection.CreateCommand();

                        check.CommandText = SQLQuery;
                        OdbcDataReader re = check.ExecuteReader();
                        int count = 0;
                        while (re.Read())
                        {
                            count = Convert.ToInt32(re["Anzahl"].ToString());
                        }

                        if (count > 0)
                            exists = true;

                        re.Close();
                        check.Dispose();
                        re.Dispose();

                    }
                }

                return exists;

            }
            catch (Exception ex)
            {
                return exists;
            }
        }

        // Handle Events (Emotes, Leave Group, Accept Group, Leave Guild,  ....)
        public void EventHandler(string whichEvent)
        {
            EventHandler(whichEvent, null);
        }

        private String GetTimestamp()
        {
            return DateTime.Now.ToString("yyyyMMddHHmmssffff"); 
        }

        private bool FTPtransfer(string FTPServer, string FTPUserName, string FTPPassword, string filename)
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPServer);
                request.Method = WebRequestMethods.Ftp.UploadFile;

                // This example assumes the FTP site uses anonymous logon.
                request.Credentials = new NetworkCredential(FTPUserName, FTPPassword);

                // Copy the contents of the file to the request stream.
                StreamReader sourceStream = new StreamReader(filename);
                byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                sourceStream.Close();
                request.ContentLength = fileContents.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                response.Close();

                return true;
            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - Unable to upload to FTP please check config");
                return false;

            }
        }

        private string getFileName()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(Application.StartupPath);
            sb.Append("\\Plugins\\WatchMyToon\\Screenshots\\");
            sb.Append(nToonId.ToString());
            sb.Append("_");
            sb.Append(GetTimestamp());
            sb.Append(".jpg");

            String directoryName = Path.GetDirectoryName(sb.ToString());

            if (!Directory.Exists(directoryName))
                Directory.CreateDirectory(directoryName);

            return sb.ToString();
        }

        // Handle Events (Emotes, Leave Group, Accept Group, Leave Guild,  ....)
        public void EventHandler(string whichEvent, string eventText)
        {

            switch (whichEvent)
            {
                case "ACCEPT_GROUP":
                    Lua.DoString("AcceptGroup();");
                    Logging.Write(Color.Purple, "[WatchMyToon] - Group invite accepted");
                    break;
                case "LEAVE_GROUP":
                    Lua.DoString("LeaveParty();");
                    OdbcCommand LEAVE_GROUP = connection.CreateCommand();
                    LEAVE_GROUP.CommandText = "UPDATE `TABToonsDetail` SET `bIsInParty` = 0 WHERE nToonId = " + nToonId + ";";
                    LEAVE_GROUP.ExecuteNonQuery();
                    LEAVE_GROUP.Dispose();
                    Logging.Write(Color.Purple, "[WatchMyToon] - Group left");
                    break;
                case "DECLINE_GROUP":
                    Lua.DoString("DeclineGroup();");
                    Logging.Write(Color.Purple, "[WatchMyToon] - Group invite declined");
                    break;
                case "INVITE_GROUP":
                    Lua.DoString("InviteUnit(\"" + eventText + "\");");
                    Logging.Write(Color.Purple, "[WatchMyToon] - Group invite send");
                    break;
                case "ACCEPT_GUILD":
                    Lua.DoString("AcceptGuild();");
                    Logging.Write(Color.Purple, "[WatchMyToon] - Guild invite accepted");
                    break;
                case "LEAVE_GUILD":
                    Lua.DoString("GuildLeave();");
                    OdbcCommand LEAVE_GUILD = connection.CreateCommand();
                    LEAVE_GUILD.CommandText = "UPDATE `TABToonsDetail` SET `bIsInGuild` = 0 WHERE nToonId = " + nToonId + ";";
                    LEAVE_GUILD.ExecuteNonQuery();
                    LEAVE_GUILD.Dispose();
                    Logging.Write(Color.Purple, "[WatchMyToon] - Guild left");
                    break;
                case "DECLINE_GUILD":
                    Lua.DoString("DeclineGuild();");
                    Logging.Write(Color.Purple, "[WatchMyToon] - Guild invite declined");
                    break;
                case "SEND_EMOTE":
                    Lua.DoString("DoEmote(\"" + eventText + "\");");
                    Logging.Write(Color.Purple, "[WatchMyToon] - Emote send");
                    break;
                case "FORCE_QUIT":
                    Lua.DoString("ForceQuit();");
                    Logging.Write(Color.Purple, "[WatchMyToon] - Game killed");
                    break;
                case "IGNORE_PLAYER":
                    Lua.DoString("AddIgnore(\"" + eventText + "\");");
                    Logging.Write(Color.Purple, "[WatchMyToon] - Player ignored");
                    break;
                case "TAKE_SCREENSHOT":
                    string file = Application.StartupPath + "\\Plugins\\WatchMyToon\\config.ini";
                    configloader confl = new configloader(file);
                    confl.load();
                    string screencapture = confl.get("EnableFTP");
                    if (screencapture.Equals("true"))
                    {
                        string filename = getFileName();
                        if (scr.CaptureWindowToFile(ObjectManager.Wow.WindowHandle, filename, System.Drawing.Imaging.ImageFormat.Jpeg))
                        {
                            if(FTPtransfer(confl.get(" FTPServer"), confl.get("FTPUserName"), confl.get("FTPUserPassword"), filename))
                                Logging.Write(Color.Green, "[WatchMyToon] - Screenshot taken and uploaded");
                        }
                        else
                        {
                            Logging.Write(Color.Red, "[WatchMyToon] - Unable to take screenshot");
                        }

                    }
                    
                    break;
                default:
                    break;
            }
        }

        // Send something to the Chat
        public void SendToWoWChat(string MessageType, string szMessage, string szReciever)
        {

            switch (MessageType)
            {
                case "WHISPER_MESSAGE":
                    Logging.Write(Color.Purple, "[WatchMyToon] - Send WHISPER_MESSAGE");
                    Lua.DoString("SendChatMessage(\"" + szMessage + "\", \"WHISPER\", nil, \"" + szReciever + "\");");
                    break;
                case "SAY_MESSAGE":
                    Logging.Write(Color.Purple, "[WatchMyToon] - Send SAY_MESSAGE");
                    Lua.DoString("SendChatMessage(\"" + szMessage + "\", \"SAY\", nil, nil);");
                    break;
                case "GUILD_MESSAGE":
                    Logging.Write(Color.Purple, "[WatchMyToon] - Send GUILD_MESSAGE");
                    Lua.DoString("SendChatMessage(\"" + szMessage + "\", \"GUILD\", nil, nil);");
                    break;
                case "YELL_MESSAGE":
                    Logging.Write(Color.Purple, "[WatchMyToon] - Send YELL_MESSAGE");
                    Lua.DoString("SendChatMessage(\"" + szMessage + "\", \"YELL\", nil, nil);");
                    break;
                case "BATTLEGROUND_MESSAGE":
                    Logging.Write(Color.Purple, "[WatchMyToon] - Send BATTLEGROUND_MESSAGE");
                    Lua.DoString("SendChatMessage(\"" + szMessage + "\", \"BATTLEGROUND\", nil, nil);");
                    break;
                case "PARTY_MESSAGE":
                    Logging.Write(Color.Purple, "[WatchMyToon] - Send PARTY_MESSAGE");
                    Lua.DoString("SendChatMessage(\"" + szMessage + "\", \"PARTY\", nil, nil);");
                    break;
                default:
                    break;

            }
        }

        // The Threadfunction
        public void DoWork()
        {
            while (!stop)
            {
                try
                {

                    if (connection.State == System.Data.ConnectionState.Open)
                    {
                        lock (connection)
                        {

                            if (last_update <= DateTime.Now.AddSeconds(-30))
                            {

                                try
                                {

                                    string Health = StyxWoW.Me.HealthPercent.ToString();
                                    string PowerType = StyxWoW.Me.PowerType.ToString();
                                    string Power = StyxWoW.Me.PowerPercent.ToString();
                                    string Money = StyxWoW.Me.Copper.ToString();
                                    string ZoneId = StyxWoW.Me.ZoneId.ToString();
                                    string SubZone = StyxWoW.Me.SubZoneText;
                                    string ZoneText = StyxWoW.Me.ZoneText;

                                    if (String.IsNullOrEmpty(ArrayClassSpec[0]))
                                    {
                                        ArrayClassSpec = getClassSpec().Split('@');
                                    }

                                    if (String.IsNullOrEmpty(Realm)) //No need to do this lua query every single time.
                                    {
                                        List<string> RealmLua = Lua.GetReturnValues("return GetRealmName()");
                                        Realm = RealmLua[0];
                                    }

                                    if (String.IsNullOrEmpty(Server))
                                        Server = Realm;

                                    if (String.IsNullOrEmpty(Side))
                                    {
                                        if (StyxWoW.Me.IsAlliance)
                                            Side = "Alliance";
                                        else
                                            Side = "Horde";
                                    }

                                    ArrayBagCount = getBagCount().Split('@');



                                    OdbcCommand Update = connection.CreateCommand();
                                    Update.CommandText = "UPDATE `TABToons` SET dtLastUpdate = CURRENT_TIMESTAMP, `szRealm` = \"" + Server + "\", `szFaction` = '" + Side + "', `szClass` = \"" + ArrayClassSpec[0] + "\", `szCurrentSpec` = \"" + ArrayClassSpec[1] + "\" WHERE nToonId = " + nToonId + ";";
                                    //Update.CommandText = "UPDATE `TABToons` SET dtLastUpdate = CURRENT_TIMESTAMP, `szRealm` = \"" + Server + "\", `szFaction` = \"" + Side + "\"  WHERE nToonId = " + nToonId + ";";

                                    Update.ExecuteNonQuery();

                                    Update.CommandText = "UPDATE `TABToonsDetail` SET `nCurrentLvl` = " + StyxWoW.Me.Level + ", `nCurrentXp` = " + StyxWoW.Me.Experience + ", `nNextLvlXp` = " + StyxWoW.Me.NextLevelExperience + ", `szPowerType` = '" + PowerType + "', `szPower` = '" + Power + "', `szHealth` = '" + Health + "', `szZoneId` = \"" + ZoneId + "\", `nZoneLevelNr` = \"" + currentZoneLevel + "\", `szSubZone` = \"" + SubZone + "\", `szZoneText` = \"" + ZoneText + "\", `szMoneyInCopper` = '" + Money + "', `nFreeBagSlot` = " + Convert.ToInt32(ArrayBagCount[0]) + ", `nTotalBagSlot` = " + Convert.ToInt32(ArrayBagCount[1]) + ", `nXposition` = " + xposition + ", `nYposition` = " + yposition + " WHERE nToonId = " + nToonId + ";";
                                    //Update.CommandText = "UPDATE `TABToonsDetail` SET `nCurrentLvl` = " + StyxWoW.Me.Level + ", `nCurrentXp` = " + StyxWoW.Me.Experience + ", `nNextLvlXp` = " + StyxWoW.Me.NextLevelExperience + ", `szPowerType` = '" + PowerType + "', `szPower` = '" + Power + "', `szHealth` = '" + Health + "', `szZoneId` = '" + ZoneId + "', `szSubZone` = '" + SubZone + "', `szZoneText` = '" + ZoneText + "', `szMoneyInCopper` = '" + Money + "', `szClass` = '" + ArrayClassSpec[0] + "', `szCurrentSpec` = '" + ArrayClassSpec[1] + "' WHERE nToonId = " + nToonId + ";";

                                    Update.ExecuteNonQuery();

                                    if (isInParty())
                                        Update.CommandText = "UPDATE `TABToonsDetail` SET `bIsInParty` = -1 WHERE nToonId = " + nToonId + ";";
                                    else
                                        Update.CommandText = "UPDATE `TABToonsDetail` SET `bIsInParty` = 0 WHERE nToonId = " + nToonId + ";";

                                    Update.ExecuteNonQuery();

                                    if (isInGuild())
                                        Update.CommandText = "UPDATE `TABToonsDetail` SET `bIsInGuild` = -1 WHERE nToonId = " + nToonId + ";";
                                    else
                                        Update.CommandText = "UPDATE `TABToonsDetail` SET `bIsInGuild` = 0 WHERE nToonId = " + nToonId + ";";

                                    Update.ExecuteNonQuery();

                                    last_update = DateTime.Now;

                                }
                                catch (Exception ex)
                                {
                                    Logging.Write(Color.Red, "[WatchMyToon] - Error while update " + ex.Message);
                                }
                            }
                        }
                        try
                        {

                            getCurrentPosition();

                            OdbcCommand command = new OdbcCommand("SELECT * FROM `TABMessageToSend` WHERE nToonId = " + nToonId + ";", connection);
                            OdbcDataReader reader = command.ExecuteReader();

                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {


                                    int nMsgId = Convert.ToInt32(reader["nMsgId"].ToString());
                                    string MESSAGE_TYPE = reader["szMessageType"].ToString();

                                    if (MESSAGE_TYPE.Equals("SAY_MESSAGE"))
                                    {
                                        if (StyxWoW.Me.IsAlive)
                                        {
                                            SendToWoWChat(MESSAGE_TYPE, reader["szMessageText"].ToString(), reader["szMessagePartner"].ToString());

                                            OdbcCommand com = new OdbcCommand("DELETE FROM `TABMessageToSend` where nMsgId = " + nMsgId + ";", connection);
                                            com.ExecuteNonQuery();
                                        }

                                    }
                                    else if (MESSAGE_TYPE.Equals("YELL_MESSAGE"))
                                    {
                                        if (StyxWoW.Me.IsAlive)
                                        {
                                            SendToWoWChat(MESSAGE_TYPE, reader["szMessageText"].ToString(), reader["szMessagePartner"].ToString());

                                            OdbcCommand com = new OdbcCommand("DELETE FROM `TABMessageToSend` where nMsgId = " + nMsgId + ";", connection);
                                            com.ExecuteNonQuery();
                                        }
                                    }
                                    else
                                    {

                                        SendToWoWChat(MESSAGE_TYPE, reader["szMessageText"].ToString(), reader["szMessagePartner"].ToString());

                                        OdbcCommand com = new OdbcCommand("DELETE FROM `TABMessageToSend` where nMsgId = " + nMsgId + ";", connection);
                                        com.ExecuteNonQuery();
                                    }

                                }
                            }
                            reader.Close();

                            // Handle GroupStuff
                            command = connection.CreateCommand();
                            command.CommandText = "SELECT * FROM `TABGroupInvites` WHERE nToonId = " + nToonId + ";";
                            reader = command.ExecuteReader();

                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    string GROUP_HANDLE = reader["szStatus"].ToString();
                                    switch (GROUP_HANDLE)
                                    {
                                        case "REQUEST_GROUP":
                                            break;
                                        case "ACCEPT_GROUP":
                                            EventHandler(GROUP_HANDLE);
                                            OdbcCommand del = connection.CreateCommand();
                                            del.CommandText = "DELETE FROM `TABGroupInvites` WHERE `nToonId` = " + nToonId + ";";
                                            del.ExecuteNonQuery();
                                            break;
                                        default:
                                            EventHandler(GROUP_HANDLE);
                                            break;
                                    }
                                }
                            }

                            reader.Close();

                            // Handle GuildStuff

                            command.CommandText = "SELECT * FROM `TABGuildInvites` WHERE nToonId = " + nToonId + ";";
                            reader = command.ExecuteReader();

                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    string GUILD_HANDLE = reader["szStatus"].ToString();
                                    switch (GUILD_HANDLE)
                                    {
                                        case "REQUEST_GUILD":
                                            break;
                                        case "ACCEPT_GUILD":
                                            EventHandler(GUILD_HANDLE);
                                            OdbcCommand del = connection.CreateCommand();
                                            del.CommandText = "DELETE FROM `TABGuildInvites` WHERE `nToonId` = " + nToonId + ";";
                                            del.ExecuteNonQuery();
                                            break;
                                        default:
                                            EventHandler(GUILD_HANDLE);
                                            break;
                                    }
                                }
                            }

                            reader.Close();

                            //Handle Events
                            command.CommandText = "SELECT * FROM `TABEventHandling` WHERE nToonId = " + nToonId + ";";
                            reader = command.ExecuteReader();

                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {

                                    int EVENT_ID = Convert.ToInt32(reader["nEventId"]);
                                    string EVENT_HANDLE = reader["szEventDesc"].ToString();
                                    string EVENT_TEXT = reader["szEventText"].ToString();

                                    if (EVENT_HANDLE.Equals("SEND_EMOTE"))
                                    {
                                        if (StyxWoW.Me.IsAlive)
                                        {
                                            EventHandler(EVENT_HANDLE, EVENT_TEXT);
                                            OdbcCommand del = connection.CreateCommand();
                                            del.CommandText = "DELETE FROM `TABEventHandling` WHERE nEventId = " + EVENT_ID + ";";
                                            del.ExecuteNonQuery();
                                        }
                                    }
                                    else if (EVENT_HANDLE.Equals("FORCE_QUIT"))
                                    {
                                        OdbcCommand del = connection.CreateCommand();
                                        del.CommandText = "DELETE FROM `TABEventHandling` WHERE nEventId = " + EVENT_ID + ";";
                                        del.ExecuteNonQuery();
                                        EventHandler(EVENT_HANDLE, EVENT_TEXT);
                                        
                                    }
                                    else
                                    {
                                        EventHandler(EVENT_HANDLE, EVENT_TEXT);
                                        OdbcCommand del = connection.CreateCommand();
                                        del.CommandText = "DELETE FROM `TABEventHandling` WHERE nEventId = " + EVENT_ID + ";";
                                        del.ExecuteNonQuery();
                                    }
                                }
                            }

                            reader.Close();


                        }
                        catch (Exception ex)
                        {
                            Logging.Write(Color.Red, "[WatchMyToon] - Error while get Message's  --> " + ex.Message);
                        }

                    }
                    else
                    {
                        connection.Open();
                    }
                }
                catch (Exception ex)
                {
                    //Logging.Write(Color.Red, "[WatchMyToon] - " + ex.Message);
                }

            }
        }

        // Clear all first
        public void Clear()
        {
            try
            {

                if (connection.State == System.Data.ConnectionState.Open)
                {
                    lock (connection)
                    {
                        OdbcCommand delete = connection.CreateCommand();
                        delete.CommandText = "DELETE FROM `TABMessageToSend` WHERE `nToonId` = " + nToonId + ";";
                        delete.ExecuteNonQuery();

                        delete.CommandText = "DELETE FROM `TABMessageReceive` WHERE `nToonId` = " + nToonId + ";";
                        delete.ExecuteNonQuery();

                        delete.CommandText = "DELETE FROM `TABEventHandling` WHERE `nToonId` = " + nToonId + ";";
                        delete.ExecuteNonQuery();

                        delete.CommandText = "DELETE FROM `TABGuildInvites` WHERE `nToonId` = " + nToonId + ";";
                        delete.ExecuteNonQuery();

                        delete.CommandText = "DELETE FROM `TABGroupInvites` WHERE `nToonId` = " + nToonId + ";";
                        delete.ExecuteNonQuery();

                        delete.CommandText = "DELETE FROM `TABLoots` WHERE `nToonId` = " + nToonId + ";";
                        delete.ExecuteNonQuery();

                        delete.Dispose();

                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        public void getCurrentPosition()
        {

            int x = 0;
            int y = 0;

            try
            {
                Lua.DoString("SetMapToCurrentZone();");

                List<string> XY = Lua.GetReturnValues("return GetPlayerMapPosition(\"player\")");

                if (XY.Count == 0)
                    return;

                NumberStyles style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
                CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
                float _x;
                float.TryParse(XY[0], style, culture, out _x);
                float _y;
                float.TryParse(XY[1], style, culture, out _y);

                _x = _x * 100;
                _y = _y * 100;


                x = (int)Math.Round(_x, 0);
                y = (int)Math.Round(_y, 0);

                x = x * 3;
                y = y * 3;

                xposition = x;
                yposition = y;

                List<string> currentZone = Lua.GetReturnValues("return GetCurrentMapDungeonLevel()");

                currentZoneLevel = Convert.ToInt32(currentZone[0].ToString());

            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - getCurrentPosition() " + ex.Message);

            }
        }

        // Get the Freebagslots and totalamount
        /*public string getBagCount()
        {
            string returnstring = "";
            int bagcount = 0;
            int bagtotalcount = 0;
            try
            {
                List<string> bagCount = Lua.GetReturnValues("return GetContainerNumFreeSlots(0)");
                bagcount += Convert.ToInt32(bagCount[0].ToString());
                bagCount.Clear();

                bagCount = Lua.GetReturnValues("return GetContainerNumFreeSlots(1)");
                bagcount += Convert.ToInt32(bagCount[0].ToString());
                bagCount.Clear();

                bagCount = Lua.GetReturnValues("return GetContainerNumFreeSlots(2)");
                bagcount += Convert.ToInt32(bagCount[0].ToString());
                bagCount.Clear();

                bagCount = Lua.GetReturnValues("return GetContainerNumFreeSlots(3)");
                bagcount += Convert.ToInt32(bagCount[0].ToString());
                bagCount.Clear();

                bagCount = Lua.GetReturnValues("return GetContainerNumFreeSlots(4)");
                bagcount += Convert.ToInt32(bagCount[0].ToString());
                bagCount.Clear();


                bagCount = Lua.GetReturnValues("return GetContainerNumSlots(0)");
                bagtotalcount += Convert.ToInt32(bagCount[0].ToString());
                bagCount.Clear();

                bagCount = Lua.GetReturnValues("return GetContainerNumSlots(1)");
                bagtotalcount += Convert.ToInt32(bagCount[0].ToString());
                bagCount.Clear();

                bagCount = Lua.GetReturnValues("return GetContainerNumSlots(2)");
                bagtotalcount += Convert.ToInt32(bagCount[0].ToString());
                bagCount.Clear();

                bagCount = Lua.GetReturnValues("return GetContainerNumSlots(3)");
                bagtotalcount += Convert.ToInt32(bagCount[0].ToString());
                bagCount.Clear();

                bagCount = Lua.GetReturnValues("return GetContainerNumSlots(4)");
                bagtotalcount += Convert.ToInt32(bagCount[0].ToString());
                bagCount.Clear();


                returnstring = bagcount.ToString() + "@" + bagtotalcount.ToString();
                return returnstring;

            }catch(Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - getBagCount() " + ex.Message);
                return returnstring;
            }
        }
*/
        // Get the Freebagslots and totalamount
        public string getBagCount()
        {
            string returnstring = "0@0";
            int bagcount = 0;
            int bagtotalcount = 0;

            try
            {
                // get the Freeslots
                for (int i = 0; i < 5; i++)
                {
                    List<string> bagCount = Lua.GetReturnValues("return GetContainerNumFreeSlots(" + i + ")");
                    bagcount += Convert.ToInt32(bagCount[0].ToString());
                    bagCount.Clear();
                }

                // get the Totallslots
                for (int i = 0; i < 5; i++)
                {
                    List<string> bagCount = Lua.GetReturnValues("return GetContainerNumSlots(" + i + ")");
                    bagtotalcount += Convert.ToInt32(bagCount[0].ToString());
                    bagCount.Clear();
                }

                returnstring = bagcount.ToString() + "@" + bagtotalcount.ToString();
                return returnstring;

            }
            catch (Exception ex)
            {
                //Logging.Write(Color.Red, "[WatchMyToon] - getBagCount() " + ex.Message);
                return returnstring;
            }
        }

        // GetClassSpec and so on
        public string getClassSpec()
        {

            string returnstring = "";

            try
            {

                List<string> ClassLua = Lua.GetReturnValues("return UnitClass(\"player\")");
                returnstring = ClassLua[1].ToString();

                List<string> TalentsLua = Lua.GetReturnValues("return GetActiveTalentGroup(false,false)");
                int TalentID = Convert.ToInt32(TalentsLua[0].ToString());

                if (TalentID != null)
                {

                    List<string> Talent = Lua.GetReturnValues("return GetPrimaryTalentTree(false, false, " + TalentID + ")");
                    string talentTabId = Talent[0].ToString();

                    if (string.IsNullOrEmpty(talentTabId))
                        returnstring += "@Unknown";
                    else
                    {

                        List<string> Talents = Lua.GetReturnValues("return GetTalentTabInfo(" + talentTabId + ", false, false)");
                        returnstring += "@" + Talents[1].ToString();
                    }

                }

                return returnstring;
            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - getClassSpec() " + ex.Message);
                return returnstring;
            }


        }

        // Pulse
        public override void Pulse()
        {
            if (doWork)
            {
                try
                {
                    if (workerThread == null)
                    {
                        workerThread = new Thread(DoWork);
                    }

                    if (!workerThread.IsAlive)
                    {

                        workerThread.Start();
                        Logging.Write(Color.Orange, "[WatchMyToon] - Updatethread started");

                    }
                }
                catch (Exception ex)
                {
                    Logging.Write(Color.Red, "[WatchMyToon] - " + ex.Message);
                }

            }
        }

        // the Plugin will be destroyed
        public override void Dispose()
        {
            IsInitialized = false;
            stop = true;
            while (workerThread.IsAlive)
            { }

            Logging.Write(Color.Green, "[WatchMyToon] - Updatethread killed");

            if (connection.State == System.Data.ConnectionState.Open)
            {
                connection.Close();
                Logging.Write(Color.Green, "[WatchMyToon] - Connection Closed");

            }
        }

        // Use this to init the Plugin
        public override void Initialize()
        {
            if (IsInitialized) return;
            try
            {
                Logging.Write(Color.Green, "[WatchMyToon] - Checking for Updates");

                Updater upt = new Updater();
                upt.CheckForUpdate(Version);

                Logging.Write(Color.Green, "[WatchMyToon] - Loading ....");

                connection = new OdbcConnection(ConStr);

                // Include all the Events here 
                Logging.Write(Color.Green, "[WatchMyToon] - Add events");
                WoWChat.Whisper += WoWChat_Whisper;
                WoWChat.Guild += WoWChat_Guild;
                WoWChat.Say += WoWChat_Say;
                WoWChat.Yell += WoWChat_Yell;
                WoWChat.Battleground += WoWChat_Battleground;
                WoWChat.Party += WoWChat_Party;

                Lua.Events.AttachEvent("LOOT_OPENED", LootTarget);
                Lua.Events.AttachEvent("OPEN_MASTER_LOOT_LIST", LootTarget);
                Lua.Events.AttachEvent("CHAT_MSG_LOOT", Loot);
                Lua.Events.AttachEvent("CHAT_MSG_MONEY", Loot);

                Lua.Events.AttachEvent("ACHIEVEMENT_EARNED", ACHIEVEMENT_EARNED);

                Lua.Events.AttachEvent("QUEST_ACCEPTED", QUEST_ACCEPTED);
                Lua.Events.AttachEvent("QUEST_WATCH_UPDATE", QUEST_WATCH_UPDATE);

                // Invite events
                Lua.Events.AttachEvent("GUILD_INVITE_REQUEST", GUILD_INVITE_REQUEST);
                Lua.Events.AttachEvent("GUILD_INVITE_CANCEL", GUILD_INVITE_CANCEL);
                Lua.Events.AttachEvent("PARTY_INVITE_REQUEST", PARTY_INVITE_REQUEST);
                Lua.Events.AttachEvent("PARTY_INVITE_CANCEL", PARTY_INVITE_CANCEL);


                //B.net 
                Lua.Events.AttachEvent("CHAT_MSG_BN_WHISPER", CHAT_MSG_BN_WHISPER);

                last_update = DateTime.Now;

                // Open Connection
                connection.Open();


                Logging.Write(Color.Green, "[WatchMyToon] - Connection Done");


                Logging.Write(Color.Green, "[WatchMyToon] - Check DBVersion");

                VersionControl();

                Logging.Write(Color.Green, "[WatchMyToon] - Register Character");

                if (connection.State == System.Data.ConnectionState.Open)
                {
                    try
                    {
                        OdbcCommand command = connection.CreateCommand();
                        command.CommandText = "SELECT * FROM `TABToons` WHERE szName = '" + StyxWoW.Me.Name + "';";

                        OdbcDataReader reader = command.ExecuteReader();

                        if (reader.HasRows)
                        {
                            Logging.Write(Color.Green, "[WatchMyToon] - Getting ID");
                            while (reader.Read())
                            {
                                nToonId = Convert.ToInt32(reader["nToonId"].ToString());
                            }

                            OdbcCommand Update = connection.CreateCommand();
                            Update.CommandText = "UPDATE `TABToons` SET `dtLastUpdate` = CURRENT_TIMESTAMP WHERE `nToonId` = " + nToonId + ";";
                            Update.ExecuteNonQuery();
                            reader.Close();
                        }
                        else
                        {
                            reader.Close();
                            Logging.Write(Color.Green, "[WatchMyToon] - Create new Record");
                            OdbcCommand command2 = connection.CreateCommand();

                            command2.CommandText = "INSERT INTO `TABToons` (`szGender`, `szRace`,`szName`,`dtLastUpdate`) VALUES ('" + StyxWoW.Me.Gender + "','" + StyxWoW.Me.Race + "','" + StyxWoW.Me.Name + "', CURRENT_TIMESTAMP);";
                            command2.ExecuteNonQuery();

                            Logging.Write(Color.Green, "[WatchMyToon] - Getting ID");
                            OdbcCommand select = new OdbcCommand("SELECT * FROM `TABToons` WHERE `szName` = '" + StyxWoW.Me.Name + "';", connection);
                            OdbcDataReader re = select.ExecuteReader();

                            ulong guildl = StyxWoW.Me.GuildLevel;

                            while (re.Read())
                            {
                                nToonId = Convert.ToInt32(re["nToonId"].ToString());
                            }

                            re.Close();

                            command2.CommandText = "INSERT INTO `TABToonsDetail` (`nToonId`, `nCurrentLvl`,`nCurrentXp`,`nNextLvlXp`) VALUES (" + nToonId + "," + StyxWoW.Me.Level + "," + StyxWoW.Me.Experience + "," + StyxWoW.Me.NextLevelExperience + ");";
                            command2.ExecuteNonQuery();



                        }
                    }
                    catch (Exception ex)
                    {
                        Logging.Write(Color.Red, "[WatchMyToon] - " + ex.Message);
                    }
                }

                Logging.Write(Color.Green, "[WatchMyToon] - Clear database");

                Clear();

                Logging.Write(Color.Green, "[WatchMyToon] - Successfully loaded");

                IsInitialized = true;
                stop = false;
            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - Unable to Connect! Please check the UserDSN");
            }

        }

        //BG Event
        private void WoWChat_Battleground(WoWChat.ChatLanguageSpecificEventArgs e)
        {
            if (connection.State == System.Data.ConnectionState.Open && e.Author != StyxWoW.Me.Name)
            {
                lock (connection)
                {
                    try
                    {

                        OdbcCommand command = connection.CreateCommand();
                        command.CommandText = "INSERT INTO `TABMessageReceive` (`nToonId`, `szMessageType`, `szMessagePartner`, `szMessageText`, `dtTime`) VALUES (" + nToonId + ",'BATTLEGROUND_MESSAGE', \"" + e.Author + "\",\"" + e.Message + "\", CURRENT_TIMESTAMP);";
                        command.ExecuteNonQuery();
                        Logging.Write(Color.Purple, "[WatchMyToon] - Received BATTLEGROUND_MESSAGE");

                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
        }

        // Whisper event
        private void WoWChat_Whisper(WoWChat.ChatWhisperEventArgs e)
        {
            if (connection.State == System.Data.ConnectionState.Open && e.Author != StyxWoW.Me.Name)
            {
                lock (connection)
                {
                    try
                    {
                        Logging.Write(Color.Purple, "[WatchMyToon] - Whisper receive");
                        OdbcCommand command = connection.CreateCommand();
                        command.CommandText = "INSERT INTO `TABMessageReceive` (`nToonId`, `szMessageType`, `szMessagePartner`, `szMessageText`, `dtTime`) VALUES (" + nToonId + ",'WHISPER_MESSAGE', \"" + e.Author + "\",\"" + e.Message + "\", CURRENT_TIMESTAMP);";
                        command.ExecuteNonQuery();
                        Logging.Write(Color.Purple, "[WatchMyToon] - Whisper Send");
                    }
                    catch (Exception ex)
                    {
                        Logging.Write(Color.Red, "[WatchMyToon] - " + ex.Message);
                    }
                }

            }
        }

        //Party Message
        private void WoWChat_Party(WoWChat.ChatLanguageSpecificEventArgs e)
        {
            if (connection.State == System.Data.ConnectionState.Open && e.Author != StyxWoW.Me.Name)
            {
                lock (connection)
                {
                    try
                    {

                        OdbcCommand command = connection.CreateCommand();
                        command.CommandText = "INSERT INTO `TABMessageReceive` (`nToonId`, `szMessageType`, `szMessagePartner`, `szMessageText`, `dtTime`) VALUES (" + nToonId + ",'PARTY_MESSAGE', \"" + e.Author + "\",\"" + e.Message + "\", CURRENT_TIMESTAMP);";
                        command.ExecuteNonQuery();

                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
        }

        //Guild Event
        private void WoWChat_Guild(WoWChat.ChatGuildEventArgs e)
        {
            if (connection.State == System.Data.ConnectionState.Open && e.Author != StyxWoW.Me.Name)
            {
                lock (connection)
                {
                    try
                    {

                        OdbcCommand command = connection.CreateCommand();
                        command.CommandText = "INSERT INTO `TABMessageReceive` (`nToonId`, `szMessageType`, `szMessagePartner`, `szMessageText`, `dtTime`) VALUES (" + nToonId + ",'GUILD_MESSAGE', \"" + e.Author + "\",\"" + e.Message + "\", CURRENT_TIMESTAMP);";
                        command.ExecuteNonQuery();

                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
        }

        // Say Event
        private void WoWChat_Say(WoWChat.ChatLanguageSpecificEventArgs e)
        {
            if (connection.State == System.Data.ConnectionState.Open && e.Author != StyxWoW.Me.Name)
            {
                lock (connection)
                {
                    try
                    {

                        OdbcCommand command = connection.CreateCommand();
                        command.CommandText = "INSERT INTO `TABMessageReceive` (`nToonId`, `szMessageType`, `szMessagePartner`, `szMessageText`, `dtTime`) VALUES (" + nToonId + ",'SAY_MESSAGE', \"" + e.Author + "\",\"" + e.Message + "\", CURRENT_TIMESTAMP);";
                        command.ExecuteNonQuery();

                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
        }

        // Yell Event
        private void WoWChat_Yell(WoWChat.ChatLanguageSpecificEventArgs e)
        {
            if (connection.State == System.Data.ConnectionState.Open && e.Author != StyxWoW.Me.Name)
            {
                lock (connection)
                {
                    try
                    {

                        OdbcCommand command = connection.CreateCommand();
                        command.CommandText = "INSERT INTO `TABMessageReceive` (`nToonId`, `szMessageType`, `szMessagePartner`, `szMessageText`, `dtTime`) VALUES (" + nToonId + ",'SAY_MESSAGE', \"" + e.Author + "\",\"" + e.Message + "\", CURRENT_TIMESTAMP);";
                        command.ExecuteNonQuery();

                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
        }

        // Loot event
        private void Loot(object sender, LuaEventArgs args)
        {
            string looted = args.Args[0].ToString();

            if (connection.State == System.Data.ConnectionState.Open)
            {
                lock (connection)
                {

                    try
                    {
                        Match match = Regex.Match(looted, @"You receive loot:.*\|\S{3}(.*)\|Hitem:(\d{1,10}):.*\[(.{1,40})\]\|h\|(?=rx(\d{1,3})|r)");
                        if (match.Success)
                        {
                            string color = match.Groups[1].Value;
                            string id = match.Groups[2].Value;
                            string name = match.Groups[3].Value;
                            string Amount;

                            if (match.Groups[4].Value == "r" || match.Groups[4].Value == "")
                                Amount = "1";
                            else
                                Amount = match.Groups[4].Value;

                            OdbcCommand command = connection.CreateCommand();
                            command.CommandText = "INSERT INTO `TABLoots` (`nToonId`, `szColor`, `szId`, `szName`, `szAmount`, `dtInsert`) VALUES (" + nToonId + ",'" + color + "','" + id + "','" + name + "','" + Amount + "', CURRENT_TIMESTAMP);";
                            command.ExecuteNonQuery();

                        }
                    }
                    catch (ArgumentException ex)
                    {

                    }
                }
            }
        }

        public void LootTarget(object sender, LuaEventArgs args)
        {
            Styx.Logic.POI.BotPoi poi = Styx.Logic.POI.BotPoi.Current;

        }

        // ACHIEVEMENT Event
        private void ACHIEVEMENT_EARNED(object sender, LuaEventArgs args)
        {
            if (connection.State == System.Data.ConnectionState.Open)
            {
                lock (connection)
                {
                    try
                    {

                        OdbcCommand command = connection.CreateCommand();
                        command.CommandText = "INSERT INTO `TABAchievements` (`nToonId`, `szAchievId`) VALUES (" + nToonId + ",'" + args.Args[0].ToString() + "');";
                        command.ExecuteNonQuery();

                        command.Dispose();

                    }
                    catch (Exception ex)
                    {

                    }
                }
            }


        }

        // QUEST_ACCEPTED Event
        private void QUEST_ACCEPTED(object sender, LuaEventArgs args)
        {
            string questTitle = string.Empty;
            string questlevel = string.Empty;
            string questID = string.Empty;
            string isComplete = string.Empty;

            List<string> QuestLua = Lua.GetReturnValues("return GetQuestLogTitle(" + args.Args[0].ToString() + ")");

            questTitle = QuestLua[0];
            questlevel = QuestLua[1];
            isComplete = QuestLua[6];
            questID = QuestLua[8];

            if (string.IsNullOrEmpty(isComplete))
                isComplete = "0";

            if (connection.State == System.Data.ConnectionState.Open)
            {
                lock (connection)
                {
                    try
                    {

                        OdbcCommand command = connection.CreateCommand();
                        command.CommandText = "INSERT INTO `TABQuestLog` (`nToonId`, `nQuestId`, `szQuestName`, `nQuestLevel`, `nComplete`) VALUES (" + nToonId + "," + Convert.ToInt32(questID) + ",'" + questTitle + "', " + Convert.ToInt32(questlevel) + "," + Convert.ToInt32(isComplete) + ");";
                        command.ExecuteNonQuery();

                    }
                    catch (Exception ex)
                    {

                    }
                }
            }

        }

        private void QUEST_WATCH_UPDATE(object sender, LuaEventArgs args)
        {
            try
            {
                Logging.Write(Color.Red, "[WatchMyToon] - QUEST_WATCH_UPDATE fired");

                string questTitle = string.Empty;
                string questlevel = string.Empty;
                string questID = string.Empty;
                string isComplete = string.Empty;

                List<string> QuestLua = Lua.GetReturnValues("return GetQuestLogTitle(" + args.Args[0].ToString() + ")");

                questTitle = QuestLua[0];
                questlevel = QuestLua[1];
                isComplete = QuestLua[6];
                questID = QuestLua[8];

                if (string.IsNullOrEmpty(isComplete))
                    isComplete = "0";

                if (connection.State == System.Data.ConnectionState.Open)
                {
                    lock (connection)
                    {
                        try
                        {

                            OdbcCommand command = connection.CreateCommand();
                            command.CommandText = "UPDATE `TABQuestLog` SET `nComplete` = " + Convert.ToInt32(isComplete) + " WHERE `nToonId` = " + nToonId + " AND `nQuestId` = " + Convert.ToInt32(questID) + ";";
                            command.ExecuteNonQuery();

                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }

                /*string questTitle = string.Empty;
                string questlevel = string.Empty;
                string questID = string.Empty;
                string isComplete = string.Empty;

                List<string> QuestLua = Lua.GetReturnValues("return GetQuestLogTitle(" + args.Args[0].ToString() + ")");

                for (int i = 0; i < QuestLua.Count; i++)
                {
                    Logging.Write(Color.Red, "[WatchMyToon] - " + QuestLua[i]);

                }

                questTitle = QuestLua[0];
                questlevel = QuestLua[1];
                isComplete = QuestLua[6];
                questID = QuestLua[8];

                if (string.IsNullOrEmpty(isComplete))
                    isComplete = "0";

                if (connection.State == System.Data.ConnectionState.Open)
                {
                    lock (connection)
                    {
                        try
                        {

                            OdbcCommand command = connection.CreateCommand();
                            command.CommandText = "UPDATE `TABQuestLog` SET `nComplete` = " + isComplete + " WHERE `nToonId` = " + nToonId + " AND `nQuestId` = " + questID + ";";
                            command.ExecuteNonQuery();

                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }*/
            }
            catch (Exception ex)
            {

            }
        }

        // GUILD_INVITE_REQUEST Event
        private void GUILD_INVITE_REQUEST(object sender, LuaEventArgs args)
        {
            if (connection.State == System.Data.ConnectionState.Open)
            {
                lock (connection)
                {
                    try
                    {

                        OdbcCommand command = connection.CreateCommand();
                        command.CommandText = "DELETE FROM  `TABGuildInvites` WHERE `nToonId` = " + nToonId + ";";
                        command.ExecuteNonQuery();
                        command.CommandText = "INSERT INTO `TABGuildInvites` (`nToonId`, `szInviterName`,`szGuildName`, `szStatus`) VALUES (" + nToonId + ",'" + args.Args[0].ToString() + "','" + args.Args[1].ToString() + "','REQUEST_GUILD');";
                        command.ExecuteNonQuery();

                        command.Dispose();

                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
        }

        // GUILD_INVITE_CANCEL Event
        private void GUILD_INVITE_CANCEL(object sender, LuaEventArgs args)
        {
            if (connection.State == System.Data.ConnectionState.Open)
            {
                lock (connection)
                {
                    try
                    {

                        OdbcCommand command = connection.CreateCommand();
                        command.CommandText = "DELETE FROM  `TABGuildInvites` WHERE `nToonId` = " + nToonId + ";";
                        command.ExecuteNonQuery();

                        command.Dispose();

                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
        }

        // PARTY_INVITE_REQUEST Event
        private void PARTY_INVITE_REQUEST(object sender, LuaEventArgs args)
        {
            if (connection.State == System.Data.ConnectionState.Open)
            {
                lock (connection)
                {
                    try
                    {

                        OdbcCommand command = connection.CreateCommand();
                        command.CommandText = "DELETE FROM  `TABGroupInvites` WHERE `nToonId` = " + nToonId + ";";
                        command.ExecuteNonQuery();
                        command.CommandText = "INSERT INTO `TABGroupInvites` (`nToonId`, `szInviterName`, `szStatus`) VALUES (" + nToonId + ",'" + args.Args[0].ToString() + "', 'REQUEST_GROUP');";
                        command.ExecuteNonQuery();

                        command.Dispose();

                    }
                    catch (Exception ex)
                    {

                    }
                }
            }

        }

        // PARTY_INVITE_CANCEL Event
        private void PARTY_INVITE_CANCEL(object sender, LuaEventArgs args)
        {
            if (connection.State == System.Data.ConnectionState.Open)
            {
                lock (connection)
                {
                    try
                    {

                        OdbcCommand command = connection.CreateCommand();
                        command.CommandText = "UPDATE `TABGroupInvites` SET szStatus = 'DECLINE_GROUP' WHERE `nToonId` = " + nToonId + ";";
                        command.ExecuteNonQuery();

                        command.Dispose();

                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
        }

        //CHAT_MSG_BN_WHISPER Event
        private void CHAT_MSG_BN_WHISPER(object sender, LuaEventArgs args)
        {

        }

        //Check if the player is in a Guild
        public bool isInGuild()
        {
            string Guild = string.Empty;

            List<string> GuildList = Lua.GetReturnValues("return IsInGuild()");
            Guild = GuildList[0];

            if (String.IsNullOrEmpty(Guild))
                return false;
            else
                return true;
        }

        // Check if the player is in a Party
        public bool isInParty()
        {
            List<string> PatryList = Lua.GetReturnValues("return GetPartyMember(1)");
            if (string.IsNullOrEmpty(PatryList[0]))
                return false;
            else
                return true;
        }


    }
}
